package security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import security.mapper.UserMapper;
import security.vo.User;

import java.util.List;

@Service("mySecurityService")
@Slf4j
public class MySecurityService implements UserDetailsService {

    // 注入申明的 PasswordEncoder 密码解析器
    @Autowired
    private PasswordEncoder passwordEncoder;

    // 注入Usermapper
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("====== loadUserByUsername =====  username={}",username);
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        // 根据数据库中对应的用户信息
        User user = userMapper.selectOne(queryWrapper);

        // 判断用户是否存在
        if(user == null){
            throw new UsernameNotFoundException("账户信息不存在！");
        }
        // 存在对应的用户信息，则将其封装，丢给security自己去解析
        log.info("user:{}",user);

        // 使用 hasAuthority 或者  hasAnyAuthority 时，采取下列配置
        // 这一项也是需要从数据库查找的，本次只是测试  登录认证，这里就写个假数据
        //List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("users");

        // 使用 hasRole 或者 hasAnyRole 时，采取如下配置
        //List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin");
        //List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_user");

        // 多个权限
        List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_user,ROLE_admin,admin");

        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                passwordEncoder.encode(user.getPassword()),admin);
    }
}
